<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager\prepay\gateway;

use addons\epay\library\Service;
use app\common\library\InviteCode;
use app\common\manager\GroupManager;
use app\common\manager\OrderManager;
use app\common\manager\PayLogManager;
use app\common\manager\UserAccountManager;
use app\common\model\Coupon;
use app\common\model\Order;
use app\common\model\RechargeOrder;
use app\common\model\Team;
use app\common\model\UserAccount;
use app\common\model\UserCoupon;
use think\Db;
use think\Exception;

class Recharge
{
    CONST METHOD = 'Recharge';

    CONST TYPE_ALIPAY = 1;
    CONST TYPE_WECHAT = 2;
    public function order($user,$request,$trans=true)
    {
        if ($trans)
            Db::startTrans();
        try {
            $prePayment = null;
            $type = $request['type'] ?? 'wechat';
            $method = $request['method'] ?? 'JSAPI';
            $userCouponId = $request['userCouponId'] ?? 0;
            $orderId = orderNum();
            $rechargeOrder = [
                'orderid'=>$orderId,
                'user_id'=>$user->id,
                'amount'=>$request['amount'],
                'paytype'=>$request['type'],
                'createtime'=>time()
            ];

            $rechargeOrderInfo =RechargeOrder::create($rechargeOrder);
            if (!$rechargeOrderInfo){
                throw new Exception('充值订单创建失败');
            }

            if ($rechargeOrderInfo->amount < 0.01){
                throw new Exception('订单金额有误，无法创建订单');
            }

            $userCouponInfo = null;
            if ($userCouponId) {
                $userCouponInfo = UserCoupon::where('id', $userCouponId)->where('user_id', $user->id)->find();
                if (!$userCouponInfo) {
                    throw new Exception('优惠券信息有误，无法使用');
                }

                if ($userCouponInfo['expires_time'] < time()) {
                    throw new Exception('优惠券已过期，无法使用');
                }

                if ($userCouponInfo['detail']!= Coupon::DETAIL_RECHARGE){
                    throw new Exception('优惠券类型有误，无法使用');
                }

                if ($userCouponInfo['block'] == UserCoupon::BLOCK_YES){
                    throw new Exception('优惠券已被使用，无法使用');
                }

            }

            $time_expire = config('app.time_expire') ?? 5;
            $time_expire = bcadd(time(), bcmul($time_expire,60));
            if ($type == 'wechat'){
                $time_expire = date('YmdHis', $time_expire);
            }else if ($type == 'alipay'){
                $time_expire = date('Y-m-d H:i:s', $time_expire);
            }
            $pref_amount = 0.00;
            $money = $real_money = bcadd($rechargeOrderInfo->amount,0,2);
            if($userCouponInfo){
                if ($userCouponInfo['limit_amount'] > $money){
                    throw new Exception('当前金额未满足优惠券使用条件，无法使用');
                }

                if($userCouponInfo['type'] == Coupon::TYPE_FULL){
                    $real_money = bcsub($money,$userCouponInfo['amount'],2);
                    $pref_amount = $userCouponInfo['amount'];
                }else if ($userCouponInfo['type'] == Coupon::TYPE_DISCOUNT && $userCouponInfo['rate'] > 0){
                    $real_money = bcdiv(bcmul($money,$userCouponInfo['rate'],2),100,2);
                    $pref_amount = bcsub($money,$real_money,2);
                }

                if (!UserCoupon::where('id', $userCouponId)->update(['block' => UserCoupon::BLOCK_YES,'update_time'=>time()])){
                    throw new Exception('优惠券使用失败，请稍后再试');
                }
            }
            $data['order'] = $orderId;
            $data['user_id'] = $user->id;
            $data['order_money'] = $money;
            $data['real_money'] = $real_money;
            $data['user_coupon_id'] = $userCouponInfo['id']??0;
            $data['pref_money'] = $pref_amount;
            $data['relation_id'] = $rechargeOrderInfo->id;
            $data['expire_time'] = strtotime($time_expire);
            $data['ct_date'] = time();
            $result = OrderManager::Order($user,$data,\app\common\model\Order::TYPE_RECHARGE,false);

            $result1 = PayLogManager::record(['user_id'=>$user->id,'method'=>self::METHOD,'type'=> $type=='alipay' ? self::TYPE_ALIPAY : self::TYPE_WECHAT,'order'=>$orderId,'money'=>$real_money,'create_time'=>time()]);
            $returnUrl = \config('app.returnUrl');
            if ($type=='wechat'){
                $notifyUrl = \config('app.notifyWechatUrl');
            }else if ($type=='alipay'){
                $notifyUrl = \config('app.notifyAlipayUrl');
            }

            if ($result['code'] == OrderManager::$successCode && $result1['code'] == PayLogManager::$successCode) {
                $result['data']['time_expire'] = strtotime($time_expire);
                if ($trans)
                    Db::commit();
                $prePayment = Service::submitOrder($real_money,$data['order'],$type,\app\common\model\Order::TYPE_ARRAY[\app\common\model\Order::TYPE_RECHARGE]['name'],$notifyUrl,$returnUrl,$method,$user->open_id,$time_expire,['relation_id'=>$rechargeOrderInfo->id]);
                //print_r($prePayment);
                if($result1['data']['id']){
                    $id = $result1['data']['id'];
                    $update = ['request'=>serialize($prePayment)];
                    PayLogManager::modify($id,$update);
                }
            }else{
                throw new Exception($result['message'].'或'.$result1['message']);
            }
            return ['code'=>1,'message'=>'success','data'=>['order'=>$result['data'],'pre_payment'=>$prePayment]];
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            return ['code'=>0,'message'=>$exception->getMessage(),'data'=>null];
        }
    }
}